# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import hashlib
import datetime

from sqlalchemy.orm import *
from dao.User import User
from dao.UtenteEnte import UtenteEnte
from dao.Ente import Ente
from dao.Access import Access
from web_lib.webutils import *
#from Environment import schema
from web_lib.session import Session
from web_lib.page import Page

@expose('/prelogin')
def prelogin(req=None, SUB=""):
    enti = Ente().select(batchSize=None)
    pageData = {'file': 'pg/login',
                "enti": enti,
                }
    return Page(req).render(pageData)

@expose('/loginnn')
@expose('/pg/login')
def loginn(req=None):
    """
    Gestione procedura di login
    """
    username = req.form.get('username')
    passwordd = req.form.get('password')
    id_ente = req.form.get('id_ente')
    #act = findAct(req)
    if not username or not req.cookies or not id_ente:
        return Page(req).redirect(req.host_url)
        #return index()
    rows = User().select(username=str(username),
                    password=hashlib.md5(username+passwordd).hexdigest())
    if len(rows) == 1:
        if rows[0].active == True:
            id_user = rows[0].id
            Session(req).start(id_user)
            #datelogin = datetime.datetime.now()
            #access = Access(req=req)
            #access.id_user = id_user
            #access.login = datelogin
            #access.persist()
            salvaInSessione(req, sezione="Main", chiave="id_oper", valore=None)
            if hasActionWeb(req,["1"]):
                if getRoleFromId(req).lower() != "admin":
                    ente = UtenteEnte().select(id_utente=id_user, batchSize=None)
                    ids = [x.id_ente for x in ente]
                    if len(ente) <1:
                        host_url = "/"
                        return Page(req).redirect(host_url)
                    if id_ente in ids:
                        schema = Ente().getRecord(id=id_ente).denominazione_breve.lower().replace(" ", "")
                        change_schema(req, schema)
                else:
                    schema = Ente().getRecord(id=id_ente).denominazione_breve.lower().replace(" ", "")
                    change_schema(req, schema)
                host_url= "/pg/main"
                return Page(req).redirect(host_url)
            else:# hasActionWeb(req,["16"]):
                host_url = "/"
                return Page(req).redirect(host_url)
        else:
            pageData = {'file': 'pg/login',
                        "attivo":False}
            return Page(req).render(pageData)
    else:
        schema = Ente().getRecord(id=id_ente).denominazione_breve.lower().replace(" ", "")
        Session(req).start(None)
        change_schema(req, schema)
        from dao.Operatore import Operatore
        rows = Operatore().select(username=str(username),
                password=hashlib.md5(username+passwordd).hexdigest())
        if len(rows) == 1:
            if rows[0].active == True and rows[0].tipo_operatore=="amministratore":
                salvaInSessione(req, sezione="Main", chiave="id_oper", valore=rows[0].id)
                salvaInSessione(req, sezione="Main", chiave="id_user", valore=None)
                host_url= "/pg/main"
                return Page(req).redirect(host_url)


            else:
                pageData = {'file': 'pg/login',
                "attivo":False}
                return Page(req).render(pageData)
        else:
            host_url = "/prelogin"
            return Page(req).redirect(host_url)


@expose('/logout')
@expose('/pg/logout')
def logout(req, SUB =""):
    """
    Gestione procedura di logout
    """
    #id_user = Session(req).getUserId()
    salvaInSessione(req, sezione="Main", chiave="id_user", valore=None)
    salvaInSessione(req, sezione="Main", chiave="id_oper", valore=None)
    salvaInSessione(req, sezione="Main", chiave="schema", valore=None)
    #Session(req).destroy()
    #datelogout = datetime.datetime.now()
    #access = Access(req=req)
    #access.id_user = id_user
    #access.logout = datelogout
    #access.persist()
    host_url= "/"
    return Page(req).redirect(host_url)
